package host

import (
	"fmt"
	"github.com/emicklei/go-restful"
	"github.com/gorilla/websocket"
	"kubeInstall/install"
	"kubeInstall/pkg/logger"
	"kubeInstall/pkg/wsconn/ssh"
	"kubeInstall/server/services/host"
	"net/http"
)

var upGrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024 * 1024 * 10,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func AddInstallToRoute(ws *restful.WebService) {
	c := new(hostHandler)
	ws.Route(ws.GET("/host/ssh/{host_id}").To(c.openSSh))
	//ws.Route(ws.GET("/host/{host_id}/{package_id}").To(c.installSysPackage))
	logger.Info("add host ssh module successfully")
}

func (h *hostHandler) openSSh(r *restful.Request, resp *restful.Response) {
	//get host info

	hostId := r.PathParameter("host_id")
	if hostId == "" {
		h.RenderError(resp, fmt.Sprintf("get host id from http query failed!"), http.StatusNotFound)
		return
	}
	data, err := host.GetHost(hostId)


	if err != nil {
		h.RenderError(resp, fmt.Sprintf("get host failed! error is: %v", err), http.StatusNotFound)
		return
	}

	//new ssh client
	opts := install.NewSshOptions(*data)
	client, err := install.NewSShClient(opts)
	if err != nil {
		h.RenderError(resp, fmt.Sprintf("new ssh client failed! error is: %v", err), http.StatusNotFound)
		return
	}

	// new ws conn
	wsConn, err := upGrader.Upgrade(resp, r.Request, nil)
	if h.HandleWsError(wsConn, err) {
		return
	}
	defer wsConn.Close()

	sws, err := ssh.NewLogicSshWsSession(80, 40, client.SshClient, wsConn)
	if h.HandleWsError(wsConn, err) {
		return
	}
	defer sws.Close()

	quitChan := make(chan bool, 3)
	sws.Start(quitChan)
	go sws.Wait(quitChan)

	<-quitChan

	//保存日志
	logger.Info(sws.LogString())
}

/*func (h *hostHandler) installSysPackage(r *restful.Request, resp *restful.Response) {
	//查询pkg信息；
	pkgId := r.PathParameter("package_id")

	if pkgId == "" {
		h.RenderError(resp, fmt.Sprintf("get package id from http  failed!"), http.StatusBadRequest)
		return
	}
	pkg, err := serviceFile.Get(pkgId)
	if err != nil {
		h.RenderError(resp, fmt.Sprintf("get package info failed! error is: %v", err), http.StatusNotFound)
		return
	}
	//查询host信息；

	hostId := r.QueryParameter("host_id")

	if hostId == "" {
		h.RenderError(resp, fmt.Sprintf("get host id from http failed!"), http.StatusBadRequest)
		return
	}

	hostInfo, err := host.GetHost(hostId)
	if err != nil {
		h.RenderError(resp, fmt.Sprintf("get host info failed! error is: %v", err), http.StatusNotFound)
		return
	}

	err = h.install(hostInfo, pkg)
	if err != nil {
		h.RenderError(resp, fmt.Sprintf("install pkg %s failed! error is: %v", pkg.Name, err), http.StatusBadRequest)
		return
	}
	h.RenderResp(resp, "", http.StatusOK)

}

func (h *hostHandler) install(host *cluster.Host, pkg *modelFile.SysPackage) error {

	sshOpt := install.NewSshOptions(*host)
	//复制安装包到目标主机
	sshClient, err := install.NewSShClient(sshOpt)
	if err != nil {
		return err
	}

	pkgFullPath := fmt.Sprintf("/root/%s", pkg.Name)
	sshClient.Copy(pkg.SavePath, pkgFullPath)
	logger.Info("send %s to %s success", pkg.Name, host.IP)
	_, err = sshClient.CmdToString(fmt.Sprintf("rpm -ivh %s", pkgFullPath), "")
	//执行安装命令
	if err != nil {
		logger.Error("install %s failed. clean env", pkg.Name)
		sshClient.CmdToString(fmt.Sprintf("rm -rf %s", pkgFullPath), "")
		return err
	}
	logger.Info("install %s to %s success", pkg.Name, host.IP)
	//使用sshclient 获取包信息更新数据库信息
	info, err := sshClient.CmdToString(fmt.Sprintf("rpm -qpi %s", pkgFullPath), "")

	if err != nil {
		logger.Error("load package info %s failed", pkg.Name)
	}

	fmt.Println(info)
	//处理字符串info,更新到db中。
	pkg.Installed = true
	pkg.Version = ""
	pkg.Arch = ""
	pkg.Comment = ""

	err = serviceFile.UpdateFile(pkg.ID, pkg)

	return err
}*/
